package com.ds.infrastructure.audit.collector.service.impl;

import com.ds.infrastructure.audit.collector.entity.RateAccess;
import com.ds.infrastructure.audit.collector.service.IRateService;
import com.google.common.collect.ImmutableList;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 作用：
 *
 * @author WeiShaoying
 * @date 2020/8/5
 */
@Service
@Slf4j
public class RateServiceImpl implements IRateService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 判断是否可以访问
     *
     * @param rateAccess
     * @return
     */
    @Override
    public boolean canAccess(RateAccess rateAccess) {
        RedisScript<Number> redisScript = new DefaultRedisScript<>(this.getLuaScript(), Number.class);
        String key = StringUtils.join(rateAccess.getPrefix(), ":", rateAccess.getKey());
        long frequency = rateAccess.getFrequency();
        Number count = redisTemplate.execute(redisScript, ImmutableList.of(key), frequency, rateAccess.getWindow());
        log.info("====Access try frequency ={}, key = {}", count, key);
        return count != null && count.intValue() <= frequency;
    }

}
